<template>


  <div style="display: flex;flex-direction: column;justify-content: center; align-items: center;">
    <el-card class="info-card" style="width:100%;">

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">

        <el-tab-pane  label="个人信息" name="userinfo">
          <el-card class="info-card" style="width:auto">

            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>个人信息</div>
                <div>
                  <el-button v-if="!isEditing" type="primary" round size="large" @click="handleEditInfo">编辑</el-button>
                  <el-button v-if="isEditing" type="primary" round size="large" @click="handleSaveInfo">保存</el-button>
                  <el-button v-if="isEditing" type="primary" round size="large" @click="handleCancelInfo">取消</el-button>
                </div>
              </div>
            </template>


            <el-descriptions :column="infoColumn">
              <el-descriptions-item>
                <Avator :is_edit="isEditing"/>
              </el-descriptions-item>
              <el-descriptions-item>
                <div style="display: flex; flex-direction: column; align-items: center;">
                  <!-- 姓名 -->
                  <div class="info_row">
                    <div class="info_row_left">姓名：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.name }}</div>
                    <div class="info_row_right" v-if="isEditing"> <el-input v-model="userinfo.name"></el-input>
                    </div>
                  </div>
                  <!-- 性别 -->
                  <div class="info_row">
                    <div class="info_row_left">性别：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.gender }}</div>
                    <el-radio-group class="info_row_right" v-if="isEditing" v-model="userinfo.gender">
                      <el-radio label="男">男</el-radio>
                      <el-radio label="女">女</el-radio>
                    </el-radio-group>
                  </div>
                  <!-- 生日 -->
                  <div class="info_row">
                    <div class="info_row_left">生日：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.birthday }}</div>
                    <div class="info_row_right" v-if="isEditing">
                      <el-date-picker v-model="userinfo.birthday" type="date" placeholder="Pick a day"
                        :disabled-date="disabledDate" size="default" />
                    </div>
                  </div>
                  <!-- 学校 -->
                  <div class="info_row">
                    <div class="info_row_left">学校：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.school }}</div>

                    <div class="info_row_right" v-if="isEditing">
                      <el-select v-model="userinfo.school" filterable placeholder="选择学校" @focus="handleGetAllSchool"
                        @change="handleChangeSchool" style="width: 240px">
                        <el-option v-for="(school, index) in schoolList" :key="index" :label="school" :value="school" />
                      </el-select>
                    </div>

                  </div>
                  <!-- 学院 -->
                  <div class="info_row">
                    <div class="info_row_left">学院：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.college }}</div>

                    <div class="info_row_right" v-if="isEditing">
                      <el-select v-model="userinfo.college" filterable placeholder="选择学院" @focus="handleGetCollege"
                        @change="handleChangeCollege" :disabled="!isSchoolSelected" style="width: 240px">
                        <el-option v-for="(college, index) in collegeList" :key="index" :label="college"
                          :value="college" />
                      </el-select>
                    </div>

                  </div>
                  <!-- 专业 -->
                  <div class="info_row">
                    <div class="info_row_left">专业：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.major }}</div>

                    <div class="info_row_right" v-if="isEditing">
                      <el-select v-model="userinfo.major" filterable placeholder="选择专业" @focus="handleGetMajor"
                        :disabled="!isCollegeSelected" style="width: 240px">
                        <el-option v-for="(major, index) in majorList" :key="index" :label="major" :value="major" />
                      </el-select>
                    </div>

                  </div>
                  <!-- 学号 -->
                  <div v-if="!isEditing" class="info_row">
                    <div class="info_row_left">学号：</div>
                    <div class="info_row_right">{{ userinfo.user_id }}</div>
                  </div>
                  <!-- 邮箱 -->
                  <div class="info_row">
                    <div class="info_row_left">邮箱：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.email }}</div>
                    <div class="info_row_right" v-if="isEditing">
                      <el-input :disabled="userinfo.email !== null && userinfo.email !== ''" type="email" v-model="userinfo.email"></el-input>
                    </div>
                  </div>
                  <!-- 手机号 -->
                  <div class="info_row">
                    <div class="info_row_left">手机号：</div>
                    <div class="info_row_right" v-if="!isEditing">{{ userinfo.phone_numbers }}</div>
                    <div class="info_row_right" v-if="isEditing"> <el-input type="number"
                        v-model="userinfo.phone_numbers"></el-input>
                    </div>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

        </el-tab-pane>

        <el-tab-pane label="更改邮箱" name="changeEmail">
          <ChangeEmail />
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="changePassword">
          <ChangePassword />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watchEffect, onActivated } from 'vue'
// import Menu from './menu.vue'
import ChangeEmail from '@/views/main/public/publicPage/changeEmail.vue'
import ChangePassword from '@/views/main/public/publicPage/changePassword.vue'
import Avator from '@/views/main/public/publicPage/avator.vue'

import { getStudentInfoApi, updateStudentInfoApi } from "@/api/student"
import { getAllSchoolApi, getCollegeBySchoolApi, getMajorByCollegeApi } from "@/api/user"
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { validateEmail, validateName } from "@/utils/regex";

onActivated(() => {
  if (history.state.activeName) {
    activeName.value = history.state.activeName
  }
})
const isEditing = ref(false);
const store = useStore()
const infoColumn = ref(2)
const userinfo = ref({
  phone_numbers: '',
  name: '',
  gender: '',
  birthday: '',
  school: '',
  college: '',
  major: '',
  user_id: '',
  email: '',
});
const rules = {
  phone_numbers: [{ required: false, message: '请输入手机号', trigger: 'blur' }],
  name: [{ required: false, message: '输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '选择性别', trigger: 'blur' }],
  birthday: [{ required: false, message: '请选择生日', trigger: 'blur' }],
  school: [{ required: false, message: '请选择学校', trigger: 'blur' }],
  college: [{ required: false, message: '请选择学院', trigger: 'blur' }],
  major: [{ required: false, message: '请选择专业', trigger: 'blur' }],
  user_id: [{ required: false, message: '请输入学号', trigger: 'blur' }],
  email: [{ required: false, message: '请输入邮箱', trigger: 'blur' }],
}
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
};
const schoolList = ref([])
const collegeList = ref([])
const majorList = ref([])
const activeName = ref('userinfo')

const handleClick = (tab: any) => {
  // 在点击标签时，更新 activeName 的值，以显示对应的标签页
  if (tab.props.name === activeName.value) return

  activeName.value = tab.props.name;
}

// 使用 computed 计算其他两个选择框的可选状态
const isSchoolSelected = computed(() => {
  return userinfo.value.school !== '';
});

const isCollegeSelected = computed(() => {
  return isSchoolSelected.value && userinfo.value.college !== '';
});
const handleChangeSchool = () => {
  userinfo.value.college = '';
  userinfo.value.major = '';
};
const handleChangeCollege = () => {
  userinfo.value.major = '';
};
watchEffect(() => {
  if (!isSchoolSelected.value) {
    userinfo.value.college = '';
    userinfo.value.major = '';
  } else if (!isCollegeSelected.value) {
    userinfo.value.major = '';
  }
});

const getStudentInfo = () => {
  getStudentInfoApi({ user_id: store.state.user.user_id }).then((response: any) => {
    // 处理成功的情况
    if (response.code === 200) {
      console.log(response);
      userinfo.value = response.data;
    } else {
      console.error(response);
    }
  });
};
const handleGetAllSchool = () => {
  getAllSchoolApi().then((response: any) => {
    schoolList.value = response.data;
  })
}
const handleGetCollege = () => {
  getCollegeBySchoolApi(userinfo.value).then((response: any) => {
    collegeList.value = response.data;
  })
}
const handleGetMajor = () => {
  getMajorByCollegeApi(userinfo.value).then((response: any) => {
    majorList.value = response.data;
  })
}
const handleAdjustInfoColumn = () => {
  if (window.innerWidth < 700) {
    infoColumn.value = 1;
  } else {
    infoColumn.value = 2;
  }
}
onMounted(() => {
  getStudentInfo()
  window.addEventListener('resize', handleAdjustInfoColumn)
  handleAdjustInfoColumn()
})

const handleEditInfo = () => {
  isEditing.value = true;
};
const handleSaveInfo = () => {
  checkForm().then(() => {
    try {
      const selectedDate = new Date(userinfo.value.birthday);
      // 将日期对象转换为本地日期字符串，格式为 'YYYY-MM-DD'
      const formattedDate = selectedDate.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-'); // 替换斜杠为短横线
      userinfo.value.birthday = formattedDate;
      userinfo.value.school = userinfo.value.school;
      userinfo.value.college = userinfo.value.college;
      userinfo.value.major = userinfo.value.major;
      ElMessage.success({
        message: '修改信息成功',
        // type: 'warning'
        duration: 5000,
      })
      updateStudentInfoApi(userinfo.value);
    } catch (error) {
      console.error('处理修改时发生错误:', error);
    } finally {
      isEditing.value = false;
      console.log('加载完成');
    };

  })

};
const handleCancelInfo = () => {
  isEditing.value = false;
  getStudentInfo();
};

const checkForm = () => {
  return new Promise((resolve, reject) => {
    // const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    // const nameReg = /^[\u4E00-\u9FA5A-Za-z0-9]+$/;
    if (!validateName(userinfo.value.name)) {
      ElMessage.warning({
        message: '请输入合法姓名',
        type: 'warning',
        duration: 5000,
      });
      return;
    }
    if (userinfo.value.school === '') {
      ElMessage.warning({
        message: '学校不能为空',
        type: 'warning',
        duration: 5000,
      })
      return;
    }
    if (userinfo.value.college === '') {
      ElMessage.warning({
        message: '学院不能为空',
        type: 'warning',
        duration: 5000,
      })
      return;
    }
    if (userinfo.value.major === '') {
      ElMessage.warning({
        message: '专业不能为空',
        type: 'warning',
        duration: 5000,
      })
      return;
    }
    if (!validateEmail(userinfo.value.email)) {
      ElMessage.warning({
        message: '请输入正确的邮箱',
        type: 'warning',
        duration: 5000,
      })
      return;
    }
    resolve(true)
  })
}

</script>

<style lang="scss" scoped>
.affix-container {
  text-align: center;
  height: 400px;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
}

.info-card {
  position: relative;
  width: 100vw;
  max-width: 1200px;
  height: auto;
  // max-height: 600px;

  align-content: center;
  margin-top: 10px;
}

.phone_icon {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}

.info_row {
  display: flex;
  justify-content: space-between;
  // width: 600px;
  margin-bottom: 30px;
  vertical-align: auto;
  align-self: center;
}

.info_row_left {
  width: 10vw;
  min-width: 100px;
  text-align: left;
  font-size: large;
}

.info_row_right {
  width: 20vw;
  min-width: 200px;
  text-align: left;
  font-size: large;

}

.el-row {
  margin-bottom: 10px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.container {
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  width: auto;
  // max-width: 1500px;
  margin: 0 auto;
  height: 100%;
}
</style>